from quantification.strategy.indicator.Indicator import IndicatorHandler
import pandas as pd
import numpy as np

from service.stock.common import TechnicalIndexUtil, ApplicationUtil


class MAIndicators(IndicatorHandler):
    '''
    macd指标
    1. 默认参数  12,26,9
    2. 快线DIF 慢线DEA  能量柱 RD
    3. 快线在0轴上方(DIF>0), 快线上穿慢线(金叉) 多头
       快线在0轴下方(DIF<0), 快线下穿慢线(死叉) 空头
    4. 背离: 价格创新高,但MACD峰值(DIF)在下降  行情反转

    '''

    def __init__(self, indicatorHandler: IndicatorHandler = None):
        self.next = indicatorHandler

    def handle(self, pd_data):
        '''
        ma处理（金叉，死叉信号，其他指标）
        :param pd_data:
        :return:
        '''
        self.volume_analysis(pd_data)
        if self.next:
            self.next.handle(pd_data)

    def golden_dead_analysis(self, pd_data, short_window=5, long_window=10):
        '''
        金叉，死叉
        :param pd_data:
        :param period:
        :return:
        '''
        (DIF, DEA, RD) = TechnicalIndexUtil.MACD(pd_data['close'])
        aaa = np.vstack((DIF, DEA, RD))
        aaa_t = aaa.T
        frame = pd.DataFrame(aaa_t, columns=['DIF', 'DEA', 'RD'])
        pd_temp = pd_data.reset_index()
        pd_temp = pd_temp.join(frame)

        pd_temp.set_index('date', inplace=True)

        gold_cross = ApplicationUtil.CROSS(pd_temp['DIF'], pd_temp['DEA'])
        death_cross = ApplicationUtil.CROSS(pd_temp['DEA'], pd_temp['DIF'])
        pd_temp.loc[:, 'gold_cross'] = gold_cross
        pd_temp.loc[:, 'death_cross'] = death_cross

        pd_data.loc[pd_temp['macd_gold_cross'] == True, 'cross'] = 1
        pd_data.loc[pd_temp['macd_death_cross'] == True, 'cross'] = -1


